package com.zp.datax.core;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Arrays;
import java.util.Date;

@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public enum ConditionUnit {

    YEARS(ChronoUnit.YEARS, 1),
    MONTHS(ChronoUnit.MONTHS, 2),
    DAYS(ChronoUnit.DAYS, 3),
    HOURS(ChronoUnit.HOURS, 4),
    MINUTES(ChronoUnit.MINUTES, 5),
    SECONDS(ChronoUnit.SECONDS, 6);

    private final TemporalUnit tUnit;
    private final int iUnit;

    public static ConditionUnit autoMatch(int iUnit) {
        return Arrays.stream(values()).filter(t -> t.iUnit == iUnit).findFirst()
                .orElseThrow(() -> new IllegalArgumentException("同步范围与单位组合有误，同步范围选择起始与结束时间时，单位只能为'none'或'年、月、日、时、分、秒'"));
    }

    public static long plus(long timeMillis, long range, int iUnit) {
        LocalDateTime localDateTime = new Date(timeMillis).toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
        LocalDateTime newLocalDateTime = localDateTime.plus(range, autoMatch(iUnit).tUnit);
        return newLocalDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

}
